const mongoose = require('mongoose');
const shortid = require('shortid');
const slug = require('slug');


const User = require('./user.model');

const ArticleSchema = new mongoose.Schema(
  {
    shortid: { type: String,default:shortid.generate},
    slug: { type: String, lowercase: true, unique: true },
    title: String,
    body: String,
    favoritedList: {
      type: [String]
    },
    favoritesCount: { type: Number, default: 0 },
    tagList: [{ type: String }],
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  },
  { versionKey: false, timestamps: true }
);

ArticleSchema.pre('validate', function (next) {
  if (!this.slug) {
    this.slugify();
  }
  next();
});

ArticleSchema.methods.slugify = function () {
  this.slug =
    slug(this.title) +
    '-' +
    ((Math.random() * Math.pow(36, 6)) | 0).toString(36);
};


ArticleSchema.methods.getFavoriteCount = function () {
  return this.favoritedList.length
}

ArticleSchema.methods.assertFavorite = function (userId) {
  return this.favoritedList.includes(userId)
}


ArticleSchema.methods.addFavorite = async function (userId) {
  if (!this.favoritedList.includes(userId)) {
    this.favoritedList.push(userId)
    await this.save()
  }

}

ArticleSchema.methods.removeFavorite = async function (userId) {
  for (let i = 0; i < this.favoritedList.length; i++) {
    if (this.favoritedList[i] === userId) {
      this.favoritedList.splice(userId, 1)
      await this.save()
    }
  }
}

ArticleSchema.methods.toJSONFor = function (user) {
  return {
    shortid: shortid.generate(),
    slug: this.slug,
    title: this.title,
    body: this.body,
    createdAt: this.createdAt,
    updatedAt: this.updatedAt,
    tagList: this.tagList,
    // 查询用户是否收藏了该文章
    favorited: user ? user.isFavorite(this._id) : false,
    favoritesCount: this.favoritesCount,
    author: this.author.toProfileJSONFor(user)
  };
};

module.exports = mongoose.models.Article || mongoose.model('Article', ArticleSchema);
